#!/bin/sh  
#auto Change ip netmask gateway scripts  
#jfedu 2017-4-11
ETHCONF=/etc/sysconfig/network-scripts/ifcfg-eth0  
HOSTS=/etc/hosts  
NETWORK=/etc/sysconfig/network  
DIR=/data/backup/`date +%Y%m%d`
NETMASK=255.255.255.0  
echo "----------------------------"
judge_ip(){
	read -p "Please enter ip Address,example 192.168.0.11 ip": IPADDR
	echo $IPADDR|grep -v "[Aa-Zz]"|grep --color -E "([0-9]{1,3}\.){3}[0-9]{1,3}"
}
count_ip(){
	count=(`echo $IPADDR|awk -F. '{print $1,$2,$3,$4}'`) 
	IP1=${count[0]}
	IP2=${count[1]}
	IP3=${count[2]}
	IP4=${count[3]}
}
ip_check()
{
judge_ip
while [ $? -ne 0 ]
do
	judge_ip
done
count_ip
while [ "$IP1" -lt 0 -o "$IP1" -ge 255 -o "$IP2" -ge 255 -o "$IP3" -ge 255 -o "$IP4" -ge 255 ]
do
	judge_ip
	while [ $? -ne 0 ]
	do
		judge_ip
	done
	count_ip
done
}

change_ip()
{   
if [ ! -d $DIR ];then  
   	mkdir -p $DIR  
fi  
echo "The Change ip address to Backup Interface eth0"  
cp $ETHCONF  $DIR  
grep "dhcp"  $ETHCONF  
if [ $? -eq 0 ];then  
	read -p "Please enter ip Address:" IPADDR  
  	sed -i 's/dhcp/static/g' $ETHCONF  
  	echo -e "IPADDR=$IPADDR\nNETMASK=$NETMASK\nGATEWAY=`echo $IPADDR|awk -F. '{print $1"."$2"."$3}'`.2" >>$ETHCONF  
  	echo "The IP configuration success. !"  
else  
  	echo -n  "Static IP has been configured,please confirm whether to modify,yes or No":  
  	read i  
fi

if  [ "$i" == "y" -o "$i" == "yes" ];then  
	ip_check
	sed -i -e '/IPADDR/d' -e '/NETMASK/d' -e '/GATEWAY/d' $ETHCONF 
	echo -e "IPADDR=$IPADDR\nNETMASK=$NETMASK\nGATEWAY=`echo $IPADDR|awk -F. '{print $1"."$2"."$3}'`.2" >>$ETHCONF  
	echo "The IP configuration success. !"  
	echo
else  
  	echo "Static IP already exists,please exit."  
  	exit $?  
fi  
}

change_hosts()
{  
  
if [ ! -d $DIR ];then  
	mkdir -p $DIR  
fi  
  
cp $HOSTS $DIR  
ip_check
host=` echo $IPADDR|sed 's/\./-/g'|awk '{print "BJ-IDC-"$0"-jfedu.net"}'`  
cat $HOSTS |grep "$host"  
if [ $? -ne 0 ];then  
	echo "$IPADDR    $host" >> $HOSTS  
  	echo "The hosts modify success "  
fi  

grep "$host" $NETWORK  
if [ $? -ne 0 ];then  
	sed -i "s/^HOSTNAME/#HOSTNAME/g" $NETWORK  
  	echo "NETWORK=$host" >>$NETWORK  
	hostname $host;su
fi  
   
}  
 
PS3="Please Select configuration ip or configuration host:"  
select i in  "modify_ip" "modify_hosts" "exit"  
 
do  
	case $i in
     		modify_ip)
     		change_ip  
		;; 
    		modify_hosts)  
     		change_hosts  
		;;
     		exit)
     		exit   
		;;
     		*)
     		echo -e "1) modify_ip\n2) modify_ip\n3)exit"  
	esac  
 
done